<template>
  <div class="app-container">
    <!-- 图片预览组件 -->
    <el-image-viewer 
      v-if="showImageViewer" 
      :url-list="[previewImageUrl]" 
      @close="showImageViewer = false"
    />
    
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学生姓名" prop="stuName">
        <el-input
          v-model="queryParams.stuName"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="学生学号" prop="stuId">
        <el-input
          v-model="queryParams.stuId"
          placeholder="请输入学生学号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="案例ID" prop="caseId">
        <el-input
          v-model="queryParams.caseId"
          placeholder="请输入案例ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <!-- <el-form-item label="完成结果上传地址，指向学生上传的任务结果" prop="resultUrl">
        <el-input
          v-model="queryParams.resultUrl"
          placeholder="请输入完成结果上传地址，指向学生上传的任务结果"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="完成时间" prop="endTime">
        <el-date-picker clearable
          v-model="queryParams.endTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择完成时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:case:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:case:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:case:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:case:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="caseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="标识ID" align="center" prop="id" />
      <el-table-column label="学生姓名" align="center" prop="stuName" />
      <el-table-column label="学生ID" align="center" prop="stuId" />
      <el-table-column label="案例ID" align="center" prop="caseId" />
      <el-table-column label="结果上传地址" align="center" prop="resultUrl" />
      <el-table-column label="案例内容" align="center" prop="resultContent" width="120">
        <template #default="scope">
          <div v-if="scope.row.resultContent" class="image-preview-cell">
            <img 
              :src="scope.row.resultContent" 
              class="table-preview-image"
              @click="showImagePreview(scope.row.resultContent)"
              alt="案例内容"
            />
          </div>
          <div v-else class="no-image-cell">
            <el-icon><Picture /></el-icon>
            <span>暂无图片</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="审核情况" align="center" prop="resultStatus">
        <template #default="scope">
          <span v-if="scope.row.resultStatus === 2">通过</span>
          <span v-else-if="scope.row.resultStatus === 1">未通过</span>
          <span v-else-if="scope.row.resultStatus === 0">未审核</span>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="完成时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:case:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:case:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生任务记录对话框 -->
    <el-dialog :title="title" v-model="open" width="550px" append-to-body>
      <el-form ref="caseRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="学生姓名" prop="stuName">
          <el-input v-model="form.stuName" placeholder="请输入学生姓名" />
        </el-form-item>
        <el-form-item label="学生ID" prop="stuId">
          <el-input v-model="form.stuId" placeholder="请输入学生ID" />
        </el-form-item>
        <!-- <el-form-item label="案例ID" prop="caseId">
          <el-input v-model="form.caseId" placeholder="请输入案例ID" />
        </el-form-item> -->
        <el-form-item label="结果上传地址" prop="resultUrl">
          <el-input v-model="form.resultUrl" placeholder="请输入完成结果上传地址" />
        </el-form-item>
        <el-form-item label="案例内容" prop="resultContent">
          <el-upload
            class="avatar-uploader"
            action=""
            :auto-upload="false"
            :on-change="handleImageChange"
            :show-file-list="false"
          >
            <img v-if="form.resultContent" :src="form.resultContent" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="审核情况" prop="resultStatus">
          <el-select v-model="form.resultStatus" placeholder="请选择审核情况">
            <el-option label="通过" :value="2" />
            <el-option label="不通过" :value="1" />
            <el-option label="未审核" :value="0" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item> -->
        <el-form-item label="完成时间" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择完成时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
/* 表格图片预览样式 */
.image-preview-cell {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60px;
}

.table-preview-image {
  width: 50px;
  height: 50px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  border: 1px solid #e0e0e0;
  transition: all 0.3s ease;
}

.table-preview-image:hover {
  transform: scale(1.1);
  border-color: #409eff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.no-image-cell {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 60px;
  color: #909399;
  font-size: 12px;
}

.no-image-cell .el-icon {
  font-size: 20px;
  margin-bottom: 4px;
}

/* 表单图片上传样式 */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
}

.avatar {
  width: 120px;
  height: 120px;
  display: block;
  object-fit: cover;
}
</style>

<script setup name="Case">
import { ref, getCurrentInstance, reactive, watch, onMounted } from "vue";
import { listSubmit, getSubmit, delSubmit, addSubmit, updateSubmit } from "@/api/coursemanagement/submit";
import { uploadImageFile } from "@/api/tool/oss";
import useUserStore from '@/store/modules/user';
import { Plus, Picture } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();
const userStore = useUserStore();

// 定义组件属性
const props = defineProps({
  caseId: {
    type: String,
    default: null
  }
});

const caseList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const showImageViewer = ref(false);
const previewImageUrl = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    stuName: null,
    stuId: null,
    caseId: props.caseId || null,
    resultUrl: null,
    resultContent: null,
    resultStatus: null,
    endTime: null
  },
  rules: {
    stuName: [
      { required: true, message: "学生姓名不能为空", trigger: "blur" }
    ],
    stuId: [
      { required: true, message: "学生ID不能为空", trigger: "blur" }
    ],
    caseId: [
      { required: true, message: "案例ID不能为空", trigger: "blur" }
    ],
  },
  imageFile: null
});

const { queryParams, form, rules } = toRefs(data);

/** 查询学生任务记录列表 */
function getList() {
  loading.value = true;
  // 根据案例ID获取学生任务记录列表
  queryParams.value.caseId = props.caseId;
  listSubmit(queryParams.value).then(response => {
    caseList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    stuName: null,
    stuId: null,
    caseId: null,
    resultUrl: null,
    resultContent: null,
    resultStatus: null,
    createBy: null,
    createTime: null,
    delFlag: null,
    endTime: null
  };
  data.imageFile = null;
  proxy.resetForm("caseRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加学生任务记录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getSubmit(_id).then(response => {
    form.value = response.data;
    // 设置create_by为当前登录用户名称
    form.value.createBy = userStore.name;
    open.value = true;
    title.value = "修改学生任务记录";
  });
}

// 处理图片上传
function handleImageChange(file) {
  data.imageFile = file.raw;
  // 创建临时URL用于预览
  form.value.resultContent = URL.createObjectURL(file.raw);
}

// 显示图片预览
function showImagePreview(imageUrl) {
  previewImageUrl.value = imageUrl;
  showImageViewer.value = true;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["caseRef"].validate(valid => {
    if (valid) {
      proxy.$modal.loading("正在提交中...");
      // 如果有图片文件，先上传图片
      if (data.imageFile) {
        uploadImageFile(data.imageFile).then(response => {
          // 图片上传成功后，将图片URL添加到表单数据中
          form.value.resultContent = response.msg;
          submitSubmitData();
        }).catch(error => {
          proxy.$modal.closeLoading();
          proxy.$modal.msgError("图片上传失败");
        });
      } else {
        // 没有图片直接提交数据
        submitSubmitData();
      }
    }
  });
}

/** 提交提交数据 */
function submitSubmitData() {
  if (form.value.id != null) {
    updateSubmit(form.value)
      .then(response => { 
        proxy.$modal.closeLoading();
        proxy.$modal.msgSuccess("修改成功");
        open.value = false;
        getList();
      })
      .catch(() => { proxy.$modal.closeLoading(); });
  } else {
    addSubmit(form.value)
      .then(response => {
        proxy.$modal.closeLoading();
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      })
      .catch(() => { proxy.$modal.closeLoading(); });
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除学生任务记录编号为"' + _ids + '"的数据项？').then(function() {
    return delSubmit(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('learning/submit/export', {
    ...queryParams.value
  }, `submit_${new Date().getTime()}.xlsx`)
}

// 监听 caseId 的变化，当变化时执行 getList()
watch(() => props.caseId, () => {
  queryParams.value.caseId = props.caseId;
  getList();
});

onMounted(() => {
  getList();
});
</script>
